package com.ai.wxy.spring.user.service;

import com.ai.spring.common.enums.ExceptionEnum;
import com.ai.spring.common.exception.ServiceException;
import com.ai.spring.common.util.IdWorker;
import com.ai.spring.common.util.Page;
import com.ai.spring.data.jpa.dao.IJpaDao;
import com.ai.wxy.spring.user.convert.UserConvert;
import com.ai.wxy.spring.user.domain.User;
import com.ai.wxy.spring.user.dto.UserDTO;
import com.ai.wxy.spring.user.query.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户服务类
 *
 * @author 石头
 * @Date 2019/10/25
 * @Version 1.0
 **/
@Service
public class UserService {
    @Autowired
    private IJpaDao<User> userDao;
    @Autowired
    private UserConvert userConvert;

    public Long addUser(UserDTO userDTO){
        // 设置一个ID
        userDTO.setId(IdWorker.getId());
        User user = userDao.save(userConvert.toEntity(userDTO));

        return user.getId();
    }

    public boolean updUser(UserDTO userDTO){
        if (userDTO.getId() == null){
            throw new ServiceException(ExceptionEnum.PARAM_ID_EXIST,"用户");
        }

        userDao.save(userConvert.toEntity(userDTO));
        return true;
    }

    public List<UserDTO> findByEntity(UserDTO userDTO){
        List<User> userList = userDao.findBySenstive(userConvert.toEntity(userDTO));
        return userConvert.toDto(userList);
    }

    public Page<UserDTO> findUserByPage(UserQuery query,Page<?> page){
        Page<User> result = userDao.queryByCriteria(query,null,page);

        Page<UserDTO> data = Page.of(userConvert.toDto(result.getData()));
        data.setCurrentPage(page.getCurrentPage());
        data.setTotalPage(result.getTotalPage());
        data.setTotalSize(result.getTotalSize());
        data.setPageSize(page.getPageSize());

        return data;
    }
}
